package com.ayu.shortlink.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.ayu.shortlink.admin.cache.AuthStateRedisCache;
import com.ayu.shortlink.admin.common.convention.result.Result;
import com.ayu.shortlink.admin.common.convention.result.Results;
import com.ayu.shortlink.admin.dto.req.UserLoginReqDTO;
import com.ayu.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.ayu.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.ayu.shortlink.admin.dto.resp.UserActualRespDTO;
import com.ayu.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.ayu.shortlink.admin.dto.resp.UserOAuthLoginRespDTO;
import com.ayu.shortlink.admin.dto.resp.UserRespDTO;
import com.ayu.shortlink.admin.service.UserService;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.scope.AuthGiteeScope;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthScopeUtils;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class UserController {
    private final UserService userService;
    private final AuthStateRedisCache stateRedisCache;

    /**
     * 查询用户信息(脱敏后)
     */
    @GetMapping("/api/short-link/admin/v1/user/{username}")
    public Result<UserRespDTO> getUserByUserName(@PathVariable("username") String username){
        return Results.success(userService.getUserByUsername(username));
    }

    /**
     * 查询用户信息(未脱敏)
     */
    @GetMapping("/api/short-link/admin/v1/actual/user/{username}")
    public Result<UserActualRespDTO> getActualUserByUserName(@PathVariable("username") String username){
        return Results.success(BeanUtil.toBean(userService.getUserByUsername(username),UserActualRespDTO.class));
    }

    /**
     * 检查用户名是否注册
     */
    @GetMapping("/api/short-link/admin/v1/user/has-username")
    public Result<Boolean> hasUserName(@RequestParam("username") String username){
        return Results.success(userService.hasUsername(username));
    }

    /**
     * 用户注册
     */
    @PostMapping("/api/short-link/admin/v1/user")
    public Result<Void> registerUser(@RequestBody UserRegisterReqDTO requestPram){
        userService.register(requestPram);
        return Results.success();
    }

    /**
     * 根据用户名更改用户信息
     */
    @PutMapping("/api/short-link/admin/v1/user")
    public Result<Void> updateUser(@RequestBody UserUpdateReqDTO requestPram){
        userService.update(requestPram);
        return Results.success();
    }

    /**
     * 用户登录
     */
    @PostMapping("/api/short-link/admin/v1/user/login")
    public Result<UserLoginRespDTO> login(@RequestBody UserLoginReqDTO requestPram){
        return Results.success(userService.login(requestPram));
    }

    /**
     * 获取授权链接并跳转到第三方授权页面
     */
    @GetMapping("/api/short-link/admin/v1/user/login/render")
    public AuthResponse  renderAuth(){
        log.info("进入render：");
        AuthRequest authRequest = getAuthRequest();
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info(authorizeUrl);
        return AuthResponse.builder().code(200).data(authorizeUrl).build();
    }

    /**
     * 第三方回调
     * 前端部分还没有搞好
     */
    @SneakyThrows
    @GetMapping("/api/short-link/admin/v1/user/login/callback")
    public Result<UserOAuthLoginRespDTO> callback(AuthCallback callback, ServletResponse servletResponse){
        log.info("进入callback： callback params：" + JSONObject.toJSONString(callback));
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> response = authRequest.login(callback);
        log.info(JSONObject.toJSONString(response));

        if (response.ok()) {
            UserOAuthLoginRespDTO user = UserOAuthLoginRespDTO.builder()
                    .username(response.getData().getUsername())
                    .token(response.getData().getToken().toString())
                    .build();
            //添加Cookies信息
            Cookie token = new Cookie("token", response.getData().getToken().toString());
            token.setPath("/");
            token.setMaxAge(60 * 60 * 24);
            Cookie username = new Cookie("username", response.getData().getUsername());
            username.setPath("/");
            username.setMaxAge(60 * 60 * 24);
            ((HttpServletResponse)servletResponse).addCookie(token);
            ((HttpServletResponse)servletResponse).addCookie(username);
            return Results.success(user);
        }
        return Results.success(null);
    }

    /**
     * 获取授权Request
     */
    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("622e39d206713ff08f6cdbe8d5e2b6141c16da9c32b454e65c20737bfb0f5fbe")
                .clientSecret("e919d3b769a75ee79d0d874498191b230b812acc94cdd87b9c2afc70d7e3d046")
                .redirectUri("http://127.0.0.1:8000/api/short-link/admin/v1/user/login/callback")
                .scopes(AuthScopeUtils.getScopes(AuthGiteeScope.USER_INFO))
                .build(), stateRedisCache);
    }

    /**
     * 检查用户是否登录
     */
    @GetMapping("/api/short-link/admin/v1/user/check-login")
    public Result<Boolean> CheckLogin(@RequestParam("username") String username,@RequestParam("token")String token){
        return Results.success(userService.hasLogin(username,token));
    }

    @DeleteMapping("/api/short-link/admin/v1/user/logout")
    public Result<Void> logout(@RequestParam("username") String username,@RequestParam("token")String token){
        userService.logout(username,token);
        return Results.success();
    }
}
